package com.hqs.rxjava;

import android.app.Application;

import com.hqs.common.utils.Log;
import com.squareup.leakcanary.LeakCanary;
import com.wenming.library.LogReport;
import com.wenming.library.save.imp.CrashWriter;
import com.wenming.library.util.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by super on 2017/7/24.
 */

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);


        initCrashReport();
    }

    private void initCrashReport() {


        try {
            String logFile = Log.getLogFileDir();

            LogReport.getInstance()
                    .setCacheSize(30 * 1024 * 1024)//支持设置缓存大小，超出后清空
                    .setLogDir(getApplicationContext(), logFile)
                    .setWifiOnly(true)//设置只在Wifi状态下上传，设置为false为Wifi和移动网络都上传
                    .setLogSaver(new CrashWriter(getApplicationContext()))//支持自定义保存崩溃信息的样式
                    .init(getApplicationContext());

            List<File> files = new ArrayList<>();
            FileUtil.findFiles(logFile, files);
            if (files != null && files.size() > 0) {
                for (File file : files) {
                    String log = fileToString(file);
                    Log.print("CrashLog: " + log);

                }
            }
            FileUtil.deleteDir(new File(logFile));
        } catch (Exception e) {
        }

    }

    public String fileToString(File file){
        StringBuffer stringBuffer = new StringBuffer();

        try {
            FileInputStream fis = new FileInputStream(file);

            int len = 0;
            byte[] bytes = new byte[1024 * 4];
            while (true){
                len = fis.read(bytes);
                if (len == - 1){
                    break;
                }
                else {
                    stringBuffer.append(new String(bytes, 0, len));
                }
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stringBuffer.toString();
    }
}
